<template>
  <section>
    <van-sticky>
      <PageHeader title="开通/升级VIP" />
    </van-sticky>

    <div class="pd10">
      <div class="pd20 bg-color-orange color-white round-box">
        <div class="text-left font-common">您当前是：<span class="font-large">{{member ? member.vip_level_str : '普通会员'}}</span></div>
        <div class="text-left mt5 font-common" v-if="member && member.vip_level>0">
          有效期：{{member.vip_level_begin_time|timeFormat('yyyy-MM-dd')}} 至 {{member.vip_level_end_time|timeFormat('yyyy-MM-dd')}}
        </div>
      </div>

      <van-radio-group v-model="vipLevel">
        <div class="pd20 mt10 bg-color-white round-box vip-meals-wrapper">
          <div class="flex flex-row flex-centerV pb10">
            <div class="flex flex-row flex-left font-large">
              服务套餐
            </div>

            <div class="flex flex-row flex-1 flex-right flex-centerV color-gray-dark font-big" @click="$router.push({name: 'VipRights'})">
              查看会员权益详细对比<i class="iconfont icon-right-arrow ml5" />
            </div>
          </div>

          <div class="flex flex-col pt10 border-top-gray mt10"
               v-for="(item, index) in vipLevels"
               :key="index"
               @click="onCheckVipLevel(item.value)" v-if="item.level > 0">
            <div class="flex flex-row flex-centerV">
              <div class="flex flex-col flex-1">
                <div class="flex flex-row flex-left font-biger strong" :class="{'color-red': vipLevel==item.value}">
                  {{item.name}}
                </div>

                <div class="flex flex-row flex-left flex-centerV font-common mt10">
                  <img :src="STATIC_BASE_URL + 'images/mp/vip'+item.level+'.png'" width="53" height="22" />
                  <span class="ml10" :class="{'color-red': vipLevel==item.value}">{{item.desc}}</span>
                </div>
              </div>

              <div class="flex flex-col">
                <div class="flex flex-row flex-left font-biger color-orange strong">
                  ￥{{item.sale_price}}
                </div>

                <div class="flex flex-row flex-left flex-centerV font-common mt10">
                  <s class="color-gray-dark">原价：￥{{item.orig_price}}</s>
                </div>
              </div>

              <div class="flex flex-row flex-center pl10">
                <van-radio :name="item.value" checked-color="#ee0a24"></van-radio>
              </div>
            </div>

            <div class="mt10 font-common color-gray-dark" v-html="item.rights.desc" v-if="item.detail_visible">

            </div>

            <div class="flex flex-row flex-center mt10 color-gray-dark" @click="toggleVipLevelDetail(item.value)">
              <i class="iconfont icon-weibiaoti1" v-if="item.detail_visible" />
              <i class="iconfont icon-xiangxia" v-else />
            </div>
          </div>

        </div>
      </van-radio-group>
    </div>

    <div class="empty-box mt10"></div>

    <div class="flex flex-col bg-color-white bottom-wrapper">
      <div class="flex flex-row flex-left pd5 font-common color-gray-dark">
        <van-checkbox v-model="checked">我同意购买VIP会员服务，且知晓一旦购买则不可退款。</van-checkbox>
      </div>
      <div class="flex flex-row flex-center">
        <div class="flex flex-col flex-1 flex-centerV font-big">
          <div class="flex flex-row flex-center color-orange">{{buyVipLevel.name}}</div>
          <div class="flex flex-row flex-center mt5">尊享VIP{{buyVipLevel.level}}特权</div>
        </div>

        <div class="flex flex-col flex-1 flex-centerV pl10 pr10">
          <van-button round block type="primary" @click="buy">立即购买</van-button>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
  import {
    STATIC_BASE_URL,
    memberVipLevelsUri,
    vipLevelOrderCreateUri,
    wxPayQueryUri,
    wxPayCreateVipLevelPayTradeUri,
    memberMyProfileUri, wechatJsApiConfigUri
  } from "../../common/api";
  import PageHeader from "../componets/PageHeader";
  import Vue from 'vue';
  import {Sticky, Popup, RadioGroup, Radio, Checkbox, Button, Toast} from 'vant';
  Vue.use(Sticky).use(Popup).use(RadioGroup).use(Radio).use(Checkbox).use(Button);
  let wxReady = false;

  export default {
    components: {
      PageHeader
    },
    data() {
      return {
        STATIC_BASE_URL: STATIC_BASE_URL,
        vipLevel: 0,
        buyVipLevel: {name: '普通会员', level: 0},

        vipLevels: [],
        member: {id: 0, user_id: 0, vip_level: 0, vip_level_str: '普通会员'},
        user: null,

        checked: true
      }
    },
    methods: {
      getVipLevels() {
        const that = this;
        const url = memberVipLevelsUri;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast.fail(msg);
          } else {
            let vipLevels = data.vip_levels;
            let i = 1;
            for (let key in vipLevels) {
              vipLevels[key]['detail_visible'] = false;
              vipLevels[key]['rights']['desc'] = vipLevels[key]['rights']['desc'].replaceAll('\n', '<br />');
              if(i == 1) {
                that.vipLevel = vipLevels[key]['value'];
                that.buyVipLevel = {
                  name: vipLevels[key]['name'],
                  level: vipLevels[key]['level']
                }
              }
              i++;
            }
            that.vipLevels = vipLevels;
          }
        }, response => {
          // error callback
        })
      },
      toggleVipLevelDetail(vipLevel) {
        let vipLevels = this.vipLevels;
        for (let key in vipLevels) {
          if(vipLevels[key].value == vipLevel) {
            vipLevels[key]['detail_visible'] = !vipLevels[key]['detail_visible'];
            break;
          }
        }
        this.vipLevels = vipLevels;
      },
      onCheckVipLevel(vipLevel) {
        this.vipLevel = vipLevel;
        let vipLevels = this.vipLevels;
        for (let key in vipLevels) {
          if(vipLevels[key].value == vipLevel) {
            this.buyVipLevel = {
              name: vipLevels[key]['name'],
              level: vipLevels[key]['level']
            };
            break;
          }
        }
      },
      buy() {
        if(!this.GLOBAL.userInfo) {
          this.$router.push({name: 'UserLogin'});
          return;
        }
        if(!this.checked) {
          this.toast('请确认您已知晓购买注意事项');
          return;
        }
        const nowtime = (new Date()).getTime() / 1000;
        const member = this.GLOBAL.memberProfile;
        if(member.vip_level_end_time > nowtime && member.vip_level > this.vipLevel) {
          this.toast('您当前的VIP服务还未过期');
          return;
        }

        const that = this;
        const fromuid = localStorage.getItem('fromuid') ? localStorage.getItem('fromuid') : 0;

        const url = vipLevelOrderCreateUri + '?fromuid=' + fromuid + '&vip_level=' + this.vipLevel;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast.fail(msg);
          } else {
            that.chooseWXPay(data.order_sn);
          }
        }, response => {
          // error callback
        })
      },
      chooseWXPay(orderSn) {
        const that = this;
        const url = wxPayCreateVipLevelPayTradeUri + '?order_sn=' + orderSn;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast.fail(msg);
          } else {
            const payParams = JSON.parse(data.pay_params);
            wx.chooseWXPay({
              timestamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: function (res) {
                // 支付成功后的回调函数
                that.onPaied(orderSn, data.pay_trade_no);
              },
              fail: function (res) {
                that.toast.fail('支付失败');
              }
            });
          }
        }, response => {
          // error callback
        });
      },
      onPaied(orderSn, payTradeNo) {
        const that = this;
        const url = wxPayQueryUri + '?pay_trade_no=' + payTradeNo;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast.fail(msg);
          } else {
            if(data.success == 1) {
              that.toast('购买成功');
              that.onPaySuccess();
            } else {
              that.toast.fail('支付出错，请重试或联系客服付款');
            }
          }
        }, response => {
          // error callback
        })
      },
      onPaySuccess() {
        const that = this;
        const url = memberMyProfileUri;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast.fail(msg);
          } else {
            that.GLOBAL.memberProfile = data.member;
            that.member = data.member;
          }
        }, response => {
          // error callback
        })
      },
      getJsApiConfig() {
        if(!isWxServiceEnable) {
          return;
        }
        const that = this;
        const url = wechatJsApiConfigUri + '?url=' + encodeURIComponent(window.location.href);
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            that.toast.fail(msg);
          } else {
            wx.config({
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: data.appId, // 必填，公众号的唯一标识
              timestamp: data.timestamp, // 必填，生成签名的时间戳
              nonceStr: data.nonceStr, // 必填，生成签名的随机串
              signature: data.signature,// 必填，签名
              jsApiList: ['hideAllNonBaseMenuItem', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'chooseWXPay'] // 必填，需要使用的JS接口列表
            });

            wx.ready(function(){
              wxReady = true;
              console.log('wx配置成功');
              wx.hideAllNonBaseMenuItem();
            });

            wx.error(function(res){
              console.log('wx配置出错');
              console.log(res);
            });
          }
        }, response => {
          // error callback
        })
      }
    },
    created: function() {
      let _href = window.location.href;
      if (isWxServiceEnable && _href.indexOf('?replace=1') <= -1) {
        window.location.replace(_href+'?replace=1');
      }
    },
    mounted: function () {
      if(this.GLOBAL.userInfo) {
        this.member = this.GLOBAL.memberProfile;
        this.user = this.GLOBAL.userInfo;
      }
      this.EventBus.$on('OnUserLogined', () => {
        this.user = this.GLOBAL.userInfo;
        this.member = this.GLOBAL.memberProfile;
      });
      this.getJsApiConfig();
      this.getVipLevels();
    }
  }
</script>

<style scoped>
  .empty-box {
    height: calc(70px +  env(safe-area-inset-bottom));
  }
  .bottom-wrapper {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding-bottom: calc(10px +  env(safe-area-inset-bottom));
  }
  .bottom-wrapper .item {
    height: 70px;
  }
  .bottom-wrapper .item .iconfont {
    font-size: 20px;
  }

  .vip-meals-wrapper .active {

  }
</style>
